package com.sqoq.downloader3.retrofit

import com.google.gson.Gson
import com.sqoq.downloader3.BuildConfig
import com.sqoq.downloader3.retrofit.gson.GsonUtil
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.concurrent.TimeUnit

/**
 * Created by Administrator on 2018/7/2 0002.
 */
class RetrofitFactory {
    private fun getHttpClient(headerGetter: HeaderGetter): OkHttpClient? {
        if (httpClient == null) {
            synchronized(RetrofitFactory::class.java) {
                if (httpClient == null) {
                    val builder = OkHttpClient.Builder()
                    builder.addInterceptor(HeaderInterceptor(headerGetter))
                    builder.connectTimeout(20, TimeUnit.SECONDS)
                        .readTimeout(20, TimeUnit.SECONDS)
                        .writeTimeout(20, TimeUnit.SECONDS)
                        .callTimeout(20, TimeUnit.SECONDS)
                    if (BuildConfig.DEBUG) {
                        builder.addInterceptor(MHttpLoggingInterceptor(HttpLogger()).setLevel(MHttpLoggingInterceptor.Level.BODY))
                    }
                    httpClient = builder.build()
                }
            }
        }
        return httpClient
    }

    fun <T> init(service: Class<T>, BASE_URL: String, headerGetter: HeaderGetter): T {

        return Retrofit.Builder().baseUrl(BASE_URL)
            .addConverterFactory(ScalarsConverterFactory.create())
//            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .addConverterFactory(GsonConverterFactory.create(GsonUtil.gson))
//            .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
            .client(getHttpClient(headerGetter)).build().create(service)
    }

    companion object {
        private var httpClient: OkHttpClient? = null
    }
}